package cn.com.nes.site.module.service.iot;

import cn.com.nes.common.annotation.AgentTransactional;
import cn.com.nes.common.annotation.OpeTransactional;
import cn.com.nes.common.em.platform.OpeMethodEnum;
import cn.com.nes.common.util.DBUtils;
import cn.com.nes.common.util.Globals;
import cn.com.nes.common.util.ParameterUtil;
import cn.com.nes.common.util.ZipUtils;
import cn.com.nes.common.wx.WechatNativePay;
import cn.com.nes.mybatis.agent.ope.entity.*;
import cn.com.nes.mybatis.agent.ope.mapper.*;
import cn.com.nes.mybatis.agent.system.entity.WxPaymentOrder;
import cn.com.nes.mybatis.agent.system.mapper.WxPaymentOrderMapper;
import cn.com.nes.site.entity.DataReq;
import cn.com.nes.site.entity.OtherData;
import cn.com.nes.site.entity.PageData;
import cn.com.nes.site.entity.dto.DtuBindUserDto;
import cn.com.nes.site.entity.em.CompanyTypeEnum;
import cn.com.nes.site.entity.em.TradeStateEnum;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapBuilder;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.db.sql.SqlBuilder;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import com.wechat.pay.java.service.payments.model.Transaction;
import org.json.JSONObject;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;

@Service
public class DtuService {

    @Resource
    private IsWxsbMapper wxsbMapper;

    @Resource
    private IsAppMapper isAppMapper;
    @Resource
    private IsVersionMapper versionMapper;

    @Resource
    private IsNormDataMapper normDataMapper;

    @Resource
    private IsDeviceProtocolDataItemInfoMapper dataItemInfoMapper;

    @Resource
    private WxPaymentOrderMapper wxPaymentOrderMapper;

    @Resource
    private RenewalInfoMapper renewalInfoMapper;

    @Resource
    private IsDeviceProtocolInfoMapper isDeviceProtocolInfoMapper;


    /**
     * dtu模块管理列表
     */
    public PageData getDtuList(DataReq req) {
        int pageId = ParameterUtil.getInteger(req, "pageId", 1);
        int pageSize = ParameterUtil.getInteger(req, "pageSize", 20);
        String protocolName = ParameterUtil.getString(req, "protocolName");
        String dtuId = ParameterUtil.getString(req, "dtuId");
        String companyType = req.getUinfo().getCompanyType();
        String manufactureId = !CompanyTypeEnum._00.getKey().equals(companyType)
                ? req.getUinfo().getNes_companyId()
                : ParameterUtil.getString(req, "manufactureId");
        String companyId = "00".equals(companyType) || "01".equals(companyType) ? "" : req.getUinfo().getCompanyId();
        // 在线状态
        Integer onlineStatus = ParameterUtil.getInteger(req, "onlineStatus");
        Page<Map<String, Object>> page = new Page<>(pageId, pageSize);
        List<Map<String, Object>> dtuList = wxsbMapper.getDtuList(page, protocolName, dtuId, manufactureId, companyId,
                onlineStatus);
        List<String> dtuIds = new ArrayList<>();
        for (Map<String, Object> map : dtuList) {
            dtuIds.add(map.get("dtuId").toString());
        }

        List<Map<String, Object>> expiredDateList = new ArrayList<>();
        if (dtuIds.size() > 0) {
            expiredDateList = renewalInfoMapper.getExpiredDateList(dtuIds, manufactureId);
        }
        Map<String, Object> expiredDateMap = new HashMap<>();
        for (Map<String, Object> map : expiredDateList) {
            expiredDateMap.put(map.get("dtuId").toString(), map.get("expiredDate"));
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (Map<String, Object> map : dtuList) {
            final Date expiredDate = (Date) expiredDateMap.get(map.get("dtuId").toString());
            map.put("expiredDate", expiredDate == null ? "" : sdf.format(expiredDate));
        }
        return PageData.ok(page, dtuList);
    }

    /**
     * 绑定协议
     */
    @OpeTransactional
    public PageData updateDtuProtocol(DataReq req, boolean unbind) {
        String dtuId = ParameterUtil.getString(req, "dtuId");
        String protocolId = unbind ? null : ParameterUtil.getString(req, "protocolId");
        final Date now = new Date();
        IsWxsb entity = new IsWxsb();
        entity.setWxId(dtuId);
        entity.setProtocolId(protocolId);
        entity.setAgentCompanyId(req.getUinfo().getCompanyId());
        entity.setVersion(now.getTime());
        entity.setXgsj(now);
        entity.setUpOper(req.getUinfo().getUsername());
        final Integer result = wxsbMapper.update(entity, new QueryWrapper<IsWxsb>().eq("wx_id", dtuId));
        if (result == 1) {
            versionMapper.updateVersion(now.getTime());
            wxsbMapper.updateEquipmentProtocol(dtuId, protocolId);
        }
        return PageData.ok();
    }

    public PageData getRealTimeData(DataReq req) {
        String dtuId = ParameterUtil.getString(req, "dtuId");
        List<Map<String, Object>> page = new ArrayList<>();
        List<IsNormData> realTimeData = normDataMapper.selectList(new QueryWrapper<IsNormData>()
                .select("other_data", "dtu_id", "create_time", "is_online", "device_protocol_id", "sb_id")
                .eq("dtu_id", dtuId));

        if (realTimeData != null && realTimeData.size() > 0) {
            for (int i = 0; i < realTimeData.size(); i++) {
                IsNormData data = realTimeData.get(i);
                final Date createTime = data.getCreateTime();
                final Integer isOnline = data.getIsOnline();
                final String protocolId = data.getDeviceProtocolId();
                if (i == 0) {
                    // 模块号
                    page.add(MapBuilder.create(new HashMap<String, Object>())
                            .put("name", "模块号")
                            .put("value", dtuId)
                            .map());
                    // 在线状态
                    page.add(MapBuilder.create(new HashMap<String, Object>())
                            .put("name", "在线状态")
                            .put("value", isOnline == 0 ? "在线" : "离线")
                            .map());
                    // 最后上报时间
                    page.add(MapBuilder.create(new HashMap<String, Object>())
                            .put("name", "最后上报时间")
                            .put("value", DateUtil.format(createTime, "yyyy-MM-dd HH:mm:ss"))
                            .map());
                }

                IsDeviceProtocolInfo query = new IsDeviceProtocolInfo();
                query.setProtocolId(protocolId);
                IsDeviceProtocolInfo deviceProtocol = isDeviceProtocolInfoMapper.selectOne(new LambdaQueryWrapper<>(query));
                List<Map<String, String>> dataItemInfos = new ArrayList<>();
                if (deviceProtocol.getIsPlc() == 1) { // 机组
                    dataItemInfos = dataItemInfoMapper.getPlcDataItemsAndField(protocolId, data.getSbId());
                } else if (deviceProtocol.getIsPlc() == 0) { // 单机
                    dataItemInfos = dataItemInfoMapper.getDataItemsAndField(protocolId);
                } else { // lora
                    continue;
                }

                // 查询协议数据项
                Map<String, Map<String, String>> dataItemMap = new HashMap<>();
                if (CollUtil.isNotEmpty(dataItemInfos)) {
                    for (Map<String, String> dataItemInfo : dataItemInfos) {
                        dataItemMap.put(dataItemInfo.get("field"),
                                MapBuilder.create(new HashMap<String, String>(2))
                                        .put("name", dataItemInfo.get("name"))
                                        .put("unit", dataItemInfo.get("unit"))
                                        .map());
                    }
                }

                // 转换other data
                final String otherData = data.getOtherData();
                if (otherData != null) {
                    List<OtherData> parsedOtherData = ZipUtils.processOtherData(otherData);
                    if (parsedOtherData != null && parsedOtherData.size() > 0) {
                        for (OtherData datum : parsedOtherData) {
                            if (dataItemMap.containsKey(datum.getF())) {
                                page.add(MapBuilder.create(new HashMap<String, Object>())
                                        .put("name", dataItemMap.get(datum.getF()).get("name"))
                                        .put("value", datum.getV())
                                        .put("unit", dataItemMap.get(datum.getF()).get("unit"))
                                        .map());
                            }
                        }
                    }
                }
            }
        }
        return PageData.ok(page);
    }

    public PageData getHistoryData(DataReq req) throws SQLException {
        Integer pageId = ParameterUtil.getInteger(req, "pageId", 1);
        Integer pageSize = ParameterUtil.getInteger(req, "pageSize", 20);
        int total = 0;
        Connection connection = null;
        List<Map<String, Object>> page = new ArrayList<>();
        final PageData ok = PageData.ok(page);

        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            connection = DBUtils.getJNDIclikchouse();
            String dtuId = ParameterUtil.getString(req, "dtuId");
            // 默认查询一天的数据
            String startTime = ParameterUtil.getDatetimeString(req, "startTime");
            String endTime = ParameterUtil.getDatetimeString(req, "endTime");
            if (StrUtil.isBlank(startTime)) {
                startTime = DateUtil.format(DateUtil.offsetDay(new Date(), -1), "yyyy-MM-dd HH:mm:ss");
            }
            if (StrUtil.isBlank(endTime)) {
                endTime = DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss");
            }
            // 获取所有的设备id
            final String sqlForEquipmentIds = SqlBuilder.create()
                    .select("distinct sb_id")
                    .from("is_norm_data_his")
                    .where(" dtu_id = ? and gmt_create >= ? and gmt_create <= ? ")
                    .build();
            ps = connection.prepareStatement(sqlForEquipmentIds, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
            ps.setString(1, dtuId);
            ps.setString(2, startTime);
            ps.setString(3, endTime);
            rs = ps.executeQuery();
            List<String> equipmentIds = new ArrayList<>();
            if (rs != null) {
                while (rs.next()) {
                    equipmentIds.add("'" + rs.getString("sb_id") + "'");
                }
                rs.close();
            }
            ps.close();
            if (equipmentIds.size() == 0) {
                return ok;
            }
            String equipmentIdPredicate;
            equipmentIdPredicate = " and sb_id in (" + CollUtil.join(equipmentIds, ",") + ") ";
            // 分页
            final String pageSql = SqlBuilder.create()
                    .select("count(1) as num")
                    .from("is_norm_data_his")
                    .where(" dtu_id = ? and create_time >= ? and create_time <= ? " + equipmentIdPredicate)
                    .build();
            ps = connection.prepareStatement(pageSql, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
            ps.setString(1, dtuId);
            ps.setString(2, startTime);
            ps.setString(3, endTime);
            rs = ps.executeQuery();
            if (rs != null) {
                while (rs.next()) {
                    total = rs.getInt("num");
                }
                rs.close();
            }
            ps.close();

            final String sql = SqlBuilder.create()
                    .select("device_protocol_id", "other_data", "create_time")
                    .from("is_norm_data_his")
                    .where(" dtu_id = ? and create_time >= ? and create_time <= ? " + equipmentIdPredicate)
                    .append(" order by create_time desc ")
                    .append(" limit " + (pageId - 1) * pageSize + "," + pageSize)
                    .build();
            ps = connection.prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
            ps.setString(1, dtuId);
            ps.setString(2, startTime);
            ps.setString(3, endTime);
            rs = ps.executeQuery();
            List<Map<String, Object>> results = new ArrayList<>();
            if (rs != null) {
                while (rs.next()) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("deviceProtocolId", rs.getString("device_protocol_id"));
                    map.put("otherData", rs.getString("other_data"));
                    map.put("createTime", rs.getString("create_time"));
                    results.add(map);
                }
            }
            if (CollUtil.isNotEmpty(results)) {
                // 查询协议数据项
                List<Map<String, String>> dataItemInfos = dataItemInfoMapper.getDataItemsAndField(results.get(0).get("deviceProtocolId").toString());
                dataItemInfos.add(MapBuilder.create(new HashMap<String, String>(2))
                        .put("name", "模块号")
                        .put("field", "dtuId")
                        .map());
                dataItemInfos.add(MapBuilder.create(new HashMap<String, String>(2))
                        .put("name", "上报时间")
                        .put("field", "createTime")
                        .map());
                ok.setExtData(dataItemInfos);
                for (Map<String, Object> result : results) {
                    final String createTime = (String) result.get("createTime");
                    final Map<String, Object> map = MapBuilder.create(new HashMap<String, Object>())
                            .put("createTime", createTime)
                            .put("dtuId", dtuId)
                            .map();
                    // 转换other data
                    final String otherData = result.get("otherData").toString();
                    if (otherData != null) {
                        List<OtherData> parsedOtherData = ZipUtils.processOtherData(otherData);
                        if (parsedOtherData != null && parsedOtherData.size() > 0) {
                            for (OtherData datum : parsedOtherData) {
                                map.put(datum.getF(), datum.getV());
                            }
                        }
                    }
                    page.add(map);
                }

            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (connection != null) {
                connection.close();
            }
            if (ps != null) {
                ps.close();
            }
            if (rs != null) {
                rs.close();
            }
        }
        ok.setPageid(pageId);
        ok.setPagesize(pageSize);
        ok.setPagecount(total / pageSize + 1);
        ok.setRecordcount(total);
        return ok;
    }

    /**
     * 生成订单
     *
     * @return
     */
    @AgentTransactional
    @OpeTransactional
    public String generateRechargeOrder(String appid, String mchid, Integer amount, long userId,
                                        String manufactureId, String username, String dtuId, int renewalDuration) {
        // 生成订单号
        final Date createTime = new Date();
        String orderNo = "rc" + DateUtil.format(createTime, "yyyyMMddHHmmssSSS")
                + RandomUtil.randomNumbers(6);
        // 生成微信支付订单
        WxPaymentOrder wxPaymentOrder = new WxPaymentOrder();
        wxPaymentOrder.setAppid(appid);
        wxPaymentOrder.setMchid(mchid);
        wxPaymentOrder.setOutTradeNo(orderNo);
        wxPaymentOrder.setTradeType("NATIVE");
        wxPaymentOrder.setTradeState(TradeStateEnum.NOTPAY.getState());
        wxPaymentOrder.setTotalAmount(amount);
        wxPaymentOrder.setPayerTotalAmount(amount);
        wxPaymentOrder.setUserId(userId);
        wxPaymentOrderMapper.insert(wxPaymentOrder);

        // 获取dtu服务到期时间
        final List<RenewalInfo> renewalInfos = renewalInfoMapper.selectList(new QueryWrapper<RenewalInfo>()
                .eq(RenewalInfo.WX_ID, dtuId)
                .eq(RenewalInfo.DELETED, 0)
                .orderByDesc(RenewalInfo.EXPIRATION_DATE)
                .last("limit 1"));
        Date expirationDate = createTime;
        if (CollUtil.isNotEmpty(renewalInfos)) {
            expirationDate = renewalInfos.get(0).getExpirationDate();
        }
        // dtu续费订单
        RenewalInfo renewalInfo = new RenewalInfo();
        renewalInfo.setOrderNumber(orderNo);
        renewalInfo.setWxId(dtuId);
        renewalInfo.setManufactureId(manufactureId);
        renewalInfo.setRenewalDate(createTime);
        renewalInfo.setExpirationDate(DateUtil.offsetDay(expirationDate, renewalDuration));
        renewalInfo.setPrice(new BigDecimal(amount / 100));
        renewalInfo.setSjly("hot_chain");
        renewalInfo.setCreateTime(createTime);
        renewalInfo.setCreateUser(username);
        renewalInfo.setUpdateTime(createTime);
        renewalInfo.setUpdateUser(username);
        renewalInfo.setDeleted(1);
        renewalInfoMapper.insert(renewalInfo);
        return orderNo;
    }

    @AgentTransactional
    public PageData createPaymentLink(DataReq req) {
        String username = req.getUinfo().getUsername();
        String dtuId = ParameterUtil.getString(req, "dtuId");
        String manufactureId = getDtuManufactureId(dtuId, req);
        long userId = Long.parseLong(req.getUinfo().getId());
        BigDecimal amount = ParameterUtil.getDecimal(req, "amount");
        int renewalDuration = ParameterUtil.getInteger(req, "renewalDuration", 365);
        if (amount == null || amount.compareTo(BigDecimal.ZERO) <= 0) {
            return PageData.error("金额错误");
        }

        final int total = amount.multiply(new BigDecimal(100)).intValue();
        // 查询是否有未支付且未过期的订单(同金额、同dtuId、同用户)
        final List<RenewalInfo> existsOrders = renewalInfoMapper.selectList(new QueryWrapper<RenewalInfo>()
                .select(RenewalInfo.ORDER_NUMBER)
                .eq(RenewalInfo.WX_ID, dtuId)
                .eq(RenewalInfo.DELETED, 1)
                .gt(RenewalInfo.CREATE_TIME, DateUtil.offsetMinute(new Date(), -5)));
        List<String> orderNos = new ArrayList<>();
        if (CollUtil.isNotEmpty(existsOrders)) {
            for (RenewalInfo existsOrder : existsOrders) {
                orderNos.add(existsOrder.getOrderNumber());
            }
            final List<WxPaymentOrder> wxPaymentOrders = wxPaymentOrderMapper.selectList(new QueryWrapper<WxPaymentOrder>()
                    .select(WxPaymentOrder.OUT_TRADE_NO, WxPaymentOrder.CODE_URL)
                    .in(WxPaymentOrder.OUT_TRADE_NO, orderNos)
                    .eq(WxPaymentOrder.TRADE_STATE, TradeStateEnum.NOTPAY.getState())
                    .eq(WxPaymentOrder.TOTAL_AMOUNT, total)
                    .gt(WxPaymentOrder.EXPIRE_TIME, new Date())
                    .eq(WxPaymentOrder.USER_ID, userId)
                    .orderByDesc(WxPaymentOrder.EXPIRE_TIME)
                    .last("limit 1"));
            if (CollUtil.isNotEmpty(wxPaymentOrders)) {
                final WxPaymentOrder wxPaymentOrder = wxPaymentOrders.get(0);
                final Map<String, Object> result = new HashMap<>();
                result.put("orderNo", wxPaymentOrder.getOutTradeNo());
                result.put("codeUrl", wxPaymentOrder.getCodeUrl());
                return PageData.ok(result);
            }
        }

        final String orderNo = generateRechargeOrder(Globals.WECHAT_PAY_APPID, Globals.WECHAT_PAY_MCHID, total, userId,
                manufactureId, username, dtuId, renewalDuration);
        // 生成支付链接
        final Map<String, Object> paymentInfo = WechatNativePay.getInstance().generatePaymentQRCode(total, "dtu续费", orderNo);
        final String codeUrl = (String) paymentInfo.get("codeUrl");
        final LocalDateTime expireTime = (LocalDateTime) paymentInfo.get("expireTime");
        // 更新订单
        WxPaymentOrder wxPaymentOrder = new WxPaymentOrder();
        wxPaymentOrder.setExpireTime(Date.from(expireTime.atZone(ZoneId.systemDefault()).toInstant()));
        wxPaymentOrder.setCodeUrl(codeUrl);
        wxPaymentOrderMapper.update(wxPaymentOrder, new QueryWrapper<WxPaymentOrder>()
                .eq(WxPaymentOrder.OUT_TRADE_NO, orderNo));

        Map<String, Object> data = new HashMap<>();
        data.put("codeUrl", codeUrl);
        data.put("orderNo", orderNo);
        return PageData.ok(data);
    }

    /**
     * 微信支付回调
     *
     * @param request
     * @return
     */
    public PageData wechatPayNotify(HttpServletRequest request) {
        try {
            final Transaction transaction = WechatNativePay.getInstance().parseNotify(request);
            final String outTradeNo = transaction.getOutTradeNo();
            final String transactionId = transaction.getTransactionId();
            final String successTime = transaction.getSuccessTime();
            final Transaction.TradeStateEnum tradeState = transaction.getTradeState();
            final Integer payerTotal = transaction.getAmount().getPayerTotal();
            final String openid = transaction.getPayer() != null ? transaction.getPayer().getOpenid() : null;

            updateOrderState(outTradeNo, transactionId, successTime, tradeState, payerTotal, openid);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return PageData.ok();
    }

    @OpeTransactional
    @AgentTransactional
    public void updateOrderState(String outTradeNo, String transactionId, String successTime,
                                 Transaction.TradeStateEnum tradeState, Integer payerTotal, String openid) {
        // 更新订单状态
        WxPaymentOrder wxPaymentOrder = new WxPaymentOrder();
        wxPaymentOrder.setTransactionId(transactionId);
        wxPaymentOrder.setTradeState(tradeState.name());
        if (StrUtil.isNotBlank(successTime)) {
            wxPaymentOrder.setSuccessTime(DateUtil.parse(successTime, "yyyy-MM-dd'T'HH:mm:ssXXX"));
        }
        wxPaymentOrder.setPayerTotalAmount(payerTotal);
        wxPaymentOrder.setPayerOpenid(openid);

        int i = wxPaymentOrderMapper.update(wxPaymentOrder, new QueryWrapper<WxPaymentOrder>()
                .eq(WxPaymentOrder.OUT_TRADE_NO, outTradeNo));

        if (i > 0 && tradeState == Transaction.TradeStateEnum.SUCCESS) {
            // 更新续费订单状态
            RenewalInfo renewalInfo = new RenewalInfo();
            renewalInfo.setDeleted(0);
            renewalInfoMapper.update(renewalInfo, new QueryWrapper<RenewalInfo>()
                    .eq(RenewalInfo.ORDER_NUMBER, outTradeNo));
        }
    }

    public PageData queryPaymentStatus(DataReq req) {
        // 订单号
        String orderNo = ParameterUtil.getString(req, "orderNo");
        List<WxPaymentOrder> wxPaymentOrders =
                wxPaymentOrderMapper.selectList(new QueryWrapper<WxPaymentOrder>()
                        .eq(WxPaymentOrder.OUT_TRADE_NO, orderNo));
        WxPaymentOrder wxPaymentOrder = wxPaymentOrders.size() > 0 ? wxPaymentOrders.get(0) : null;
        if (wxPaymentOrder == null) {
            return PageData.error("订单不存在");
        }
        Map<String, Object> data = new HashMap<>();
        final String tradeState = wxPaymentOrder.getTradeState();
        final TradeStateEnum tradeStateEnum = TradeStateEnum.getEnum(tradeState);
        data.put("tradeState", tradeState);
        data.put("tradeStateDesc", tradeStateEnum != null ? tradeStateEnum.getDesc() : "");
        return PageData.ok(data);
    }

    public PageData getRenewalPackage(DataReq req) {
        Map<String, Object> package1 = MapBuilder.create(new HashMap<String, Object>(3))
                .put("packageId", "1")
                .put("packageName", "1年")
                .put("packagePrice", 100)
                .put("duration", 365)
                .build();
        Map<String, Object> package2 = MapBuilder.create(new HashMap<String, Object>(3))
                .put("packageId", "2")
                .put("packageName", "2年")
                .put("packagePrice", 200)
                .put("duration", 730)
                .build();
        Map<String, Object> package3 = MapBuilder.create(new HashMap<String, Object>(3))
                .put("packageId", "3")
                .put("packageName", "3年")
                .put("packagePrice", 300)
                .put("duration", 1095)
                .build();
        return PageData.ok(Arrays.asList(package1, package2, package3));
    }

    public PageData queryPaymentStatusBySelf(DataReq req) {
        // 订单号
        String orderNo = ParameterUtil.getString(req, "orderNo");
        // 主动查询订单状态
        final Transaction transaction = WechatNativePay.getInstance().queryPaymentStatus(orderNo);
        if (transaction != null) {
            updateOrderState(orderNo, transaction.getTransactionId(), transaction.getSuccessTime(),
                    transaction.getTradeState(), transaction.getAmount().getPayerTotal(),
                    transaction.getPayer() != null ? transaction.getPayer().getOpenid() : null);
            Map<String, Object> data = new HashMap<>();
            final String tradeState = transaction.getTradeState().name();
            final TradeStateEnum tradeStateEnum = TradeStateEnum.getEnum(tradeState);
            data.put("tradeState", tradeState);
            data.put("tradeStateDesc", tradeStateEnum != null ? tradeStateEnum.getDesc() : "");
            return PageData.ok(data);
        }
        return PageData.error("订单不存在");
    }

    public PageData getCardInfo(DataReq req) {
        String dtuId = ParameterUtil.getString(req, "dtuId");
        if (StrUtil.isBlank(dtuId)) {
            return PageData.error("dtuId不能为空");
        }
        // 查询dtu信息
        final List<IsWxsb> dtus = wxsbMapper.selectList(new QueryWrapper<IsWxsb>()
                .select(IsWxsb.WX_KH)
                .eq(IsWxsb.WX_ID, dtuId));
        if (dtus.size() == 0) {
            return PageData.error("dtu不存在");
        }
        final String iccid = dtus.get(0).getWxKh();
        if (StrUtil.isBlank(iccid)) {
            return PageData.error("dtu未绑定物联卡");
        }
        PageData pageData;
        try {
            String url = OpeMethodEnum.getCardInfo.url();
            HttpResponse<JsonNode> response = Unirest.post(url)
                    .header("Content-Type", "application/json")
                    .header("key", req.getKey())
                    .body(JSONObject.wrap(MapBuilder.create(new HashMap<String, Object>(1))
                            .put("iccid", iccid)
                            .build()).toString())
                    .asJson();
            if (response.getStatus() == 200) {
                JSONObject body = response.getBody().getObject();
                if (body.getInt("code") == 0) {
                    pageData = PageData.ok(body.getJSONObject("data").toMap());
                    return pageData;
                } else {
                    final String msg = body.getString("msg");
                    return PageData.error(StrUtil.isNotBlank(msg) ? msg : "未查询到流量信息");
                }
            }
        } catch (UnirestException ignored) {
        }
        return PageData.error("查询失败");
    }

    public String getDtuManufactureId(String dtuId, DataReq req) {
        String companyType = ParameterUtil.getString(req, "companyType");
        if ("01".equals(companyType)) {
            return req.getUinfo().getNes_companyId();
        }

        if (StrUtil.isBlank(dtuId)) {
            return null;
        }
        // 查询dtu信息
        final List<IsWxsb> DTUs = wxsbMapper.selectList(new QueryWrapper<IsWxsb>()
                .select(IsWxsb.MANUFACTURE_ID)
                .eq(IsWxsb.WX_ID, dtuId));
        return CollUtil.isNotEmpty(DTUs) ? DTUs.get(0).getManufactureId() : null;
    }

    public PageData addMyDev(DataReq req) {
        String dtuId = ParameterUtil.getString(req, "dtuId");
        if (StrUtil.isBlank(dtuId)) {
            return PageData.error("dtuId不允许为空");
        }
        if (dtuId.indexOf("id=") > 0) {
            dtuId = dtuId.split("id=", -1)[1].trim();
        }

        if (dtuId.indexOf("***") > 0) {
            dtuId = dtuId.substring(0, dtuId.indexOf("***"));
        }

        String devName = ParameterUtil.getString(req, "devName");
        DtuBindUserDto dtuBindUser = wxsbMapper.getDtuBindUser(dtuId);
        if(ObjectUtil.isNull(dtuBindUser)) {
            return PageData.error("请确认该设备在线,如果是新绑定设备，请5分钟后再重新绑定!");
        }
        Map<String, Object> data =new HashMap<>();
        IotMyDev iotMyDevParame = new IotMyDev();
        String sbID = dtuBindUser.getSbId();
        String protocolName = dtuBindUser.getName();
        iotMyDevParame.setDtuId(dtuId);
        iotMyDevParame.setSbId(sbID);
        iotMyDevParame.setDevName(devName);
        iotMyDevParame.setUserId(req.getUinfo().getUserId());
        data.put("dtuId",dtuId);
        data.put("sbId",sbID);
        data.put("userId",req.getUinfo().getId());
        data.put("devName",devName);

        // 设备类型 1 热泵 2空调 3环境检监测 4 空气净化 5 风机盘管 6 智能开关
        int devType = 1;
        String imagepath = "";
        String type = "";
        String fields = "";
        String sceneIds = "";

        if (protocolName.indexOf("环境") > 0) {
            devType = 3;
        }

        if (protocolName.indexOf("风") > 0) {
            devType = 5;
        }

        switch (devType) {
            case 1: // 热泵
                imagepath = "image/product/1.jpg";
                fields = "a189(进水),a142(出水),a350(开关机),a415(设定值),a351(模式)";
                sceneIds = "1,2,3,4,5,6,7,8";
                break;
            case 3: // 环境监测
                imagepath = "image/product/wg1.jpg";
                fields = "a4(温度),a5(湿度),a1(PM2.5),a6(二氧化碳),a7(甲醛),a2(PM10)";
                sceneIds = "1,2,3,4,5,6,7,8";
                break;
            case 5: // 热风机
                imagepath = "image/product/rfj.jpg";
                fields = "a350(开关机),a352(设定值),a351(模式),风速(a929),环境温度(a647),盘管温度(a385)";
                sceneIds = "1,2,3,4,5,6,7,8";
                break;
            default:
                imagepath = "image/product/1.jpg";
                fields = "a189(进水),a142(出水),a350(开关机),a415(设定值),a351(模式)";
                sceneIds = "1,2,3,4,5,6,7,8";
                break;
        }

        type = String.valueOf(devType);
        iotMyDevParame.setType(type);
        iotMyDevParame.setFields(fields);
        iotMyDevParame.setSceneIds(sceneIds);
        iotMyDevParame.setImagepath(imagepath);
        data.put("userId",type);
        data.put("fields",fields);
        data.put("sceneIds",sceneIds);
        data.put("imagepath",imagepath);
        IotMyDev iotMyDev = isAppMapper.getSbid(iotMyDevParame);
        if(ObjectUtil.isNull(iotMyDev))  {
            isAppMapper.insertIotMyDev(iotMyDevParame);
            return PageData.ok(data);
        }
        return PageData.error("设备已绑定!");
    }
}
